package com.wzh.mail;

import com.rabbitmq.client.Channel;
import com.wzh.yebServe.pojo.Employee;
import com.wzh.yebServe.pojo.MailConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @Author wzh
 * @create 2022/11/21 20:50
 * @Description: 消息接收者
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class MailReceiver {

    private final JavaMailSender javaMailSender;

    private final MailProperties mailProperties;

    private final TemplateEngine templateEngine;

    private final RedisTemplate redisTemplate;


    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel)  {
        Employee employee = (Employee) message.getPayload();
        System.out.println("MailReceiver:  employee = " + employee);
        MessageHeaders headers = message.getHeaders();
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        System.out.println("tag = " + tag);
        String msgId = (String) headers.get("spring_returned_message_correlation");
        System.out.println("msgId = " + msgId);
        HashOperations hash = redisTemplate.opsForHash();

        try {
            if (hash.entries("mail_log").containsKey(msgId)){
                log.error("消息已经被消费================={}",msgId);
                /**
                 * 手动确认消息
                 * tag:消息序号
                 * multiple:是否确认多条
                 */
                channel.basicAck(tag,false);
                return;
            }
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(msg);
             //  设置发件人
            mimeMessageHelper.setFrom(mailProperties.getUsername());
             //收件人
            mimeMessageHelper.setTo(employee.getEmail());

            mimeMessageHelper.setSubject("入职欢迎邮件");

            mimeMessageHelper.setSentDate(new Date());

//            邮件内容
            Context context=new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("posName",employee.getDepartment().getName());
            context.setVariable("jobLevelName",employee.getJobLevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
//            发送邮件
             mimeMessageHelper.setText(mail,true);
             javaMailSender.send(msg);
             log.info("邮件发送成功");
//             将消息存入redis
                hash.put("mail_log",msgId,"OK");
//                手动确认消息
                channel.basicAck(tag,false);
        } catch (Exception e) {
            try {
//                退回消息
                channel.basicNack(tag,false, true);
            } catch (IOException ioException) {
             log.error("邮件发送失败=============={}",e.getMessage());
            }
            log.error("邮件发送失败=============={}",e.getMessage());
        }
    }


}
